package com.example.demo.tools.otherTools;

import com.alibaba.fastjson.JSON;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Map;


public class PostResponseUtil {

	 /**
	   * 向指定 URL 发送POST方法的请求
	   * 
	   * @param url
	   *      发送请求的 URL
	   * @param param
	   *      请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	   * @return 所代表远程资源的响应结果
	 * @throws UnsupportedEncodingException 
	   */
	public static Map sendPost(String url, Map<String, String> param,  
          String charset) throws UnsupportedEncodingException {  

      StringBuffer buffer = new StringBuffer();  
      if (param != null && !param.isEmpty()) {  
          for (Map.Entry<String, String> entry : param.entrySet()) {  
              buffer.append(entry.getKey()).append("=")  
                     .append(URLEncoder.encode(entry.getValue(),"UTF-8"))
                     /* .append(URLEncoder.encode(entry.getValue()))*/
                      /*.append(entry.getValue())  */
                      .append("&");  

          }  
      }   
      buffer.deleteCharAt(buffer.length() - 1);  
      PrintWriter out = null;  
      BufferedReader in = null;  
      String result = "";  
      Map mapTypes=null;
      try {  
          URL realUrl = new URL(url);  
          // 打开和URL之间的连接  
          URLConnection conn = realUrl.openConnection();  
          // 设置通用的请求属性  
          conn.setRequestProperty("accept", "*/*");  
          conn.setRequestProperty("connection", "Keep-Alive");  
          conn.setRequestProperty("user-agent",  
                  "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");  
          // 发送POST请求必须设置如下两行  
          conn.setDoOutput(true);  
          conn.setDoInput(true);  
          // 获取URLConnection对象对应的输出流  
          OutputStreamWriter out1 = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
          out = new PrintWriter(out1);  
          // 发送请求参数  
          out.print(buffer);  
          // flush输出流的缓冲  
          out.flush();  
          // 定义BufferedReader输入流来读取URL的响应  
          in = new BufferedReader(new InputStreamReader(  
                  conn.getInputStream(), charset));
          String line;
          while ((line = in.readLine()) != null) {
              result += line;
          }
          mapTypes = JSON.parseObject(result);
//          System.out.println("这个是用JSON类的parseObject来解析JSON字符串!!!");
//          for (Object obj : mapTypes.keySet()){
//              System.out.println("key为："+obj+"值为："+mapTypes.get(obj));
//          }
        
      } catch (Exception e) {  
          System.out.println("发送 POST 请求出现异常！" + e);  
          e.printStackTrace();  
      }  
      // 使用finally块来关闭输出流、输入流  
      finally {  
          try {  
              if (out != null) {  
                  out.close();  
              }  
              if (in != null) {  
                  in.close();  
              }  
          } catch (IOException ex) {  
              ex.printStackTrace();  
          }  
      }  
      return mapTypes;  
  }  
//	public static void main(String[] args) throws UnsupportedEncodingException {
//		Map param=new HashMap<String, String>();
//		param.put("userId", "哈哈");
//		Map<String, Object> map = PostResponseUtil.sendPost("http://192.168.13.239:8080/oa/activitiBack/startBidThree",
//				param, "utf-8");
//	}
}
